/* eslint-disable default-case */
import { message } from 'antd';
import moment from 'moment';
import {
  accuAdjustList,
  offDeclare,
  successDeclare,
  cancelDeclare,
  accuAdjustRemark,
  accuAdjustAddRemark,
  signPro,
  getProList,
  insertProbFdbk,
  getProBaseList,
  cancelProbFlag,
  dicList,
  accuAdjustDetail,
  accuInforDetail,
  updateZodiacYM,
  queryEntryAdjDet,
  detailRemark,
  getDownInfor,
  addHdlRemark,
  uploadFileBatch,
  uploadFileModify,
} from '@/services/accuadjust';
import { getUploadProgress } from '@/services/careermange';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'accuadjust';

export default {
  namespace,
  state: {
    execAdjId: '',
    adjdetData: {},
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proFormFieldsValue: {},
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    },
    detail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insAccuInfoVo: {},
      adjDetList: [],
      accuRemark: [],
    },
    inforDetail: [],
    detailHdl: [],
    accuType: [],
    proBaseList: {},
    proFbList: [],
    proVno: 0,
    tabList: [
      { itemCode: '1', itemName: '待申报' },
      { itemCode: '2', itemName: '申报中' },
      { itemCode: '3', itemName: '已申报' },
      { itemCode: '5', itemName: '问题人员' },
      { itemCode: '4', itemName: '已取消' },
    ],
    activeKey: '1',
    formFieldsValue: {},
    expandForm: false,
    disabledYmFlag: false,
    batchQuery: {
      // // 批量上传数据
      areaId: null,
      contType: null,
      progressPercent: 0,
    },
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: null, // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
  },

  effects: {
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(accuAdjustList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // 修改生效年月
    *updateZodiacYM({ payload }, { call, put }) {
      const zodiacRes = yield call(updateZodiacYM, payload);
      const { execAdjId } = payload;
      if (zodiacRes.success) {
        message.success('修改成功');
        const detailRes = yield call(accuAdjustDetail, { execAdjId });
        if (detailRes.success) {
          yield put({
            type: 'getDetail',
            payload: detailRes.data,
          });
        } else {
          message.warning(detailRes.message);
        }
      } else {
        message.warning(zodiacRes.message);
      }
    },
    *fetchInforDetail({ payload }, { call, put }) {
      const response = yield call(accuInforDetail, payload);

      if (response.success) {
        yield put({
          type: 'getInforDetail',
          payload: {
            data: response.data,
          },
        });
      }
    },
    // 查询调整明细（修改页面）
    *queryEntryAdjDet({ payload }, { call, put }) {
      const res = yield call(queryEntryAdjDet, payload);
      if (res.success) {
        yield put({
          type: 'entryAdjDet',
          payload: res.data,
        });
      } else {
        message.warning(res.message);
      }
      return res.data;
    },
    *accuOffDeclare({ payload }, { call }) {
      const response = yield call(offDeclare, payload);
      if (!response.success) {
        message.warning(response.message || '服务器端错误！');
      }
      return response;
    },
    *accuSuccessDeclare({ payload }, { call }) {
      const response = yield call(successDeclare, payload);
      if (!response.success) {
        message.warning(response.message || '服务器端错误！');
      }
      return response;
    },
    *accuCancelDeclare({ payload }, { call }) {
      const response = yield call(cancelDeclare, payload);
      if (!response.success) {
        message.warning(response.message || '服务器端错误！');
      }
      return response;
    },
    // 列表办理备注
    *remarkOk({ payload }, { call }) {
      const res = yield call(addHdlRemark, payload);
      if (!res.success === true) {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },

    *addHdlRemark({ payload, callback }, { call, select, put }) {
      const response = yield call(accuAdjustAddRemark, payload);
      const accuEmpOrdId = yield select(state => state.accuadjust.detail.accuEmpOrdId);

      if (response.success) {
        callback(response);
        const resAgin = yield call(detailRemark, {
          sendId: payload.sendId,
          busiId: accuEmpOrdId,
        });
        if (resAgin.success) {
          yield put({
            type: 'updateData',
            payload: resAgin.data,
          });
        } else {
          message.warning(resAgin.message);
        }
      }
    },
    // 办理备注详情
    *detailHdlRemark({ payload }, { call, put }) {
      const response = yield call(accuAdjustRemark, payload);
      if (response.success) {
        yield put({
          type: 'getHdlRemark',
          payload: response.data,
        });
      }
    },

    *fetchDicList({ payload }, { call, put }) {
      const response = yield call(dicList, payload);
      if (response.success) {
        yield put({
          type: 'dicListType',
          payload: {
            data: response.data,
          },
        });
      }
    },
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(accuAdjustDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      }
    },
    // 标记问题人员
    *signPro({ payload, callback }, { call }) {
      const response = yield call(signPro, payload);
      if (callback) {
        callback(response);
      }
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getProList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // 获取问题人员详情
    *fetchProBaseList({ payload }, { call, put }) {
      const response = yield call(getProBaseList, payload);
      if (response.success) {
        yield put({
          type: 'getProBaseList',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    // 社保服务办理问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(insertProbFdbk, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },
    // 反馈并取消
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(cancelProbFlag, payload);
      if (callback) {
        callback(response);
      }
    },
    *fetchDownInfor({ payload }, { call, put }) {
      const response = yield call(getDownInfor, payload);
      if (response.success) {
        yield put({
          type: 'getDownInfor',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
      const api = payload.type === 'batch' ? uploadFileBatch : uploadFileModify;
      const response = yield call(api, payload.formData);
      if (response.success) {
        if (response.data && response.data.successProp !== 100) {
          const { batchId } = response.data;
          const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

          yield put.resolve({
            type: `socket/${SocketActions.subSocketChannel}`,
            payload: {
              batchTask,
            },
          });
        } else {
          yield put({
            type: 'updateBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '上传失败'}`);
      }
      return response;
    },
    {type:'throttle',ms:10000}
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.accuadjust);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 获取列表
    entryAdjDet(state, { payload }) {
      // 根据回盘状态判断年月是否可用
      const currentDateYM = moment().format('YYYYMM');
      const { rtnStateFlag } = payload;
      const minus = moment(payload.validDate).format('YYYYMM') - currentDateYM;
      let disabledYmFlag = false;
      if (Number(rtnStateFlag) === 1) {
        // 已回盘
        if (minus <= 1) {
          disabledYmFlag = true;
        }
      }
      if (Number(rtnStateFlag) === 2) {
        // 未回盘
        if (minus <= 0) {
          disabledYmFlag = true;
        }
      }
      return {
        ...state,
        adjdetData: payload,
        disabledYmFlag,
      };
    },
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    getHdlRemark(state, { payload }) {
      return {
        ...state,
        detailHdl: Array.isArray(payload) ? payload : [],
      };
    },
    dicListType(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        accuType: data.ACCU_ADJ_TYPE,
      };
    },
    // 获取详情
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    getInforDetail(state, { payload }) {
      return {
        ...state,
        inforDetail: payload,
      };
    },
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proListData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    updateData(state, { payload }) {
      const accuRemark = payload;
      return {
        ...state,
        detail: { ...state.detail, accuRemark },
      };
    },
    getProBaseList(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbks,
      };
    },
    getDownInfor(state, { payload }) {
      if (payload.mutilTempletPath) {
        const newState = state;
        const fileId = payload.mutilTempletPath.split('|')[0];
        const fileName = payload.mutilTempletPath.split('|')[1];
        newState.fileId = fileId;
        newState.fileName = fileName;
      }
      return {
        ...state,
      };
    },
    // 设置页签状态
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });

              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });

              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
